package com.atguigu.nio;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class NIOClient {
    public static void main(String[] args) throws FileNotFoundException {
        nioClient();
    }

    public static void nioClient() {
        try {

            String[] sends = {
                    "https://pic.cnblogs.com/avatar/1345194/20180308181944.png",
                    "https://pic.cnblogs.com/avatar/1345194/20180308181944.png"
            };

            for (int i = 0; i < sends.length; i++) {
                File file = new File("D:\\data\\aa\\" + i + ".png");
                FileOutputStream outputStream = new FileOutputStream(file);
                output(outputStream, sends[i]);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void output(OutputStream out, String url) throws IOException {
        //1. 获取通道
        SocketChannel sChannel = SocketChannel.open();
        //设置 10s 超时时间
        sChannel.socket().connect(new InetSocketAddress("127.0.0.1", 9090), 10000);

        //1.2 将阻塞的套接字 变为 非阻塞 的
        sChannel.configureBlocking(false);

        //2. 创建指定大小的缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);
        System.out.println("发送：" + url);
        sChannel.write(ByteBuffer.wrap(url.getBytes()));
        // 主动关闭输出但不关闭通道，通知服务端当前发送请求已经完毕，等待服务端响应
        sChannel.shutdownOutput();

        int len = 0;
        int count = 0;
        int anInt = -1;
        boolean statusRead = false;
        //循环读取服务端返回到通道的数据，直到达到末尾
        while ((len = sChannel.read(buf)) != -1) {
            buf.flip();
            if (!statusRead && buf.limit() > 0) {
                //读取第一位标识成功或失败的 Int 值
                anInt = buf.getInt();
                statusRead = true;
            }
            if (anInt == 1) {
                if (len > 0) {
                    count += buf.limit() - buf.position();
                }
                //输出到本地磁盘
                out.write(buf.array(), buf.position(), buf.limit() - buf.position());

            } else if (anInt == 0) {
                //失败
                System.out.println("服务端请求图片资源失败!");
                System.out.println(new String(buf.array(), buf.position(), buf.limit() - buf.position(), StandardCharsets.UTF_8));
            }
            buf.clear();
        }
        out.close();
        System.out.println("返回最终大小：" + count);
        //关闭通道
        sChannel.close();
    }
}
